package com.cchc.k8s.apis;

import com.alibaba.fastjson.JSONObject;
import com.cchc.k8s.config.K8sException;
import com.cchc.k8s.kernel.IngressBuilder;
import com.cchc.k8s.request.CreateIngressRequest;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.ExtensionsV1beta1Api;
import io.kubernetes.client.openapi.models.ExtensionsV1beta1Ingress;
import io.kubernetes.client.openapi.models.ExtensionsV1beta1IngressList;
import io.kubernetes.client.openapi.models.V1Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * file：IngressApi.java
 * description: Ingress api
 * date: 2021-10-12 16:37
 * author: wenrui
 * version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/ingress")
public class IngressApi {

    @Autowired
    ApiClient apiClient;
    @Autowired
    IngressBuilder ingressBuilder;

    /**
     * 创建ingres
     *
     * @param nsName  命名空间名称
     * @param request 创建ingres请求体
     * @return String
     */
    @PostMapping("/create/{nsName}")
    public ExtensionsV1beta1Ingress createIngress(@PathVariable("nsName") String nsName, @RequestBody CreateIngressRequest request) {
        log.info("创建命名空间{}下的Ingress，请求参数为：{}", nsName, JSONObject.toJSONString(request));
        ExtensionsV1beta1Api extensionsV1beta1Api = new ExtensionsV1beta1Api(apiClient);
        ExtensionsV1beta1Ingress namespacedIngress;
        try {
            ExtensionsV1beta1Ingress ingress = ingressBuilder.builder(request);
            log.info("构建Ingress对象完成：{}", JSONObject.toJSONString(ingress.toString()));
            namespacedIngress = extensionsV1beta1Api.createNamespacedIngress(nsName, ingress, "true", null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("创建命名空间：{}下的Ingress 失败：{}", nsName, e.getResponseBody());
            throw new K8sException("I" + e.getCode(), e.getResponseBody());
        }
        log.info("创建命名空间：{}下的Ingress成功，信息为：{}", nsName, namespacedIngress.toString());
        return namespacedIngress;
    }

    @GetMapping("/detail/{nsName}/{ingressName}")
    public ExtensionsV1beta1Ingress detailIngress(@PathVariable String nsName, @PathVariable String ingressName) {
        ExtensionsV1beta1Api extensionsV1beta1Api = new ExtensionsV1beta1Api(apiClient);
        ExtensionsV1beta1Ingress ingress;
        try {
            ingress = extensionsV1beta1Api.readNamespacedIngress(ingressName + "-igs", nsName, "true", null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("查询命名空间：{}下的Ingress 失败：{}", nsName, e.getResponseBody());
            throw new K8sException("I" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        log.error("查询命名空间：{}下的Ingress成功，响应信息：{}", nsName, ingress.toString());
        return ingress;
    }

    @GetMapping("/list/{nsName}")
    public ExtensionsV1beta1IngressList listIngress(@PathVariable String nsName) {
        ExtensionsV1beta1Api extensionsV1beta1Api = new ExtensionsV1beta1Api(apiClient);
        ExtensionsV1beta1IngressList ingressList;
        try {
            ingressList = extensionsV1beta1Api.listNamespacedIngress(nsName, "true", null, null, null, null, null, null, null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("查询命名空间：{}下的Ingress 失败：{}", nsName, e.getResponseBody());
            throw new K8sException("I" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        log.error("查询命名空间：{}下的Ingress成功，响应信息：{}", nsName, ingressList.toString());
        return ingressList;
    }

    @DeleteMapping("/delete/{nsName}/{ingressName}")
    public V1Status deleteIngress(@PathVariable String nsName,@PathVariable String ingressName){
        ExtensionsV1beta1Api extensionsV1beta1Api = new ExtensionsV1beta1Api(apiClient);
        V1Status v1Status;
        try {
            v1Status = extensionsV1beta1Api.deleteNamespacedIngress(ingressName + "-igs", nsName, "true", null, null, null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("删除命名空间：{}下的Ingress 失败：{}", nsName, e.getResponseBody());
            throw new K8sException("I" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        if (v1Status != null && Objects.equals(v1Status.getStatus(), "Success")) {
            log.info("删除命名空间：{}下的Ingress：{}成功，信息：{}", nsName, ingressName, JSONObject.toJSONString(v1Status));
        }

        return v1Status;
    }
}
